package cn.net.shuxing.yifu.common.service;


import cn.net.shuxing.yifu.common.bean.User;
import cn.net.shuxing.yifu.common.bean.UserInfoBind;
import cn.net.shuxing.yifu.common.bean.UserRealInfo;
import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.constant.OssConstant;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.mapper.UserRealInfoMapper;
import cn.net.shuxing.yifu.common.util.CommonExample;
import cn.net.shuxing.yifu.common.util.HttpUtils;
import cn.net.shuxing.yifu.common.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.servlet.ServletContext;
import java.io.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

@Service
public class UserRealInfoService extends BaseService<UserRealInfo, UserRealInfoMapper> {

    //    public String idCardNo;
//    public String realName;
    private String bucketName = OssConstant.ossBucketName;
    @Autowired
    private CardTypeService cardTypeService;

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private OssCommonService ossCommonService;

    @Autowired
    private UserInfoBindService userInfoBindService;

    @Autowired
    private UserService userService;

//    public List<UserRealInfo> getsByRealName(String realName) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("realName", realName);
//        List<UserRealInfo> userRealInfos = this.gets(map);
//        return userRealInfos;
//    }

    public List<UserRealInfo> getsByRealName(String realName) {
        CommonExample commonExample = new CommonExample(UserRealInfo.class);
        commonExample.equals("realName", realName);
        List<UserRealInfo> userRealInfos = getsByExampleWithoutComplete(commonExample);
        return userRealInfos;
    }

    public UserRealInfo getByPhoneNum(String phoneNum) {
        UserInfoBind userInfoBind = userInfoBindService.getByPhoneNum(phoneNum);
        Integer id = 0;
        if (userInfoBind == null) {
        } else {
            id = userInfoBind.getId();
        }
        return getByPrimaryKey(id);
    }

    public UserRealInfo getByIdCardNum(String idCardNum) {
        UserRealInfo userRealInfo = new UserRealInfo();
        userRealInfo.clearCreateTimeAndUpdateTime();
        userRealInfo.setIdCardNum(idCardNum);
        return get(userRealInfo);
    }

    /**
     * 身份证实名认证
     */
    public boolean verify(String idCardNo, String realName) {
        String host = "http://vipidcardcheck.haoservice.com";
        String path = "/idcard/VerifyIdcardv2";
        String method = "GET";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("cardNo", idCardNo);
        // TODO: 2019-05-30  上线需要打开 转码
//        try {
//            realName = new String(realName.getBytes("ISO-8859-1"), "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        System.out.println("接口出入的realName" + realName);
        querys.put("realName", realName);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            获取response的body
            String responseStr = EntityUtils.toString(response.getEntity());
            JSONObject responseJson = (JSONObject) JSON.parse(responseStr);
            JSONObject result = (JSONObject) responseJson.get("result");
            Boolean isOk = result.getBoolean("isok");
            System.out.println("身份证第三方结果" + responseJson);
            return isOk;
//            JsonElement isOk = result.get("isOk");
//            return isOk.getAsBoolean();
//            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 身份证实名认证
     */
    public boolean verifyForBack(String idCardNo, String realName) {
        String host = "http://vipidcardcheck.haoservice.com";
        String path = "/idcard/VerifyIdcardv2";
        String method = "GET";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("cardNo", idCardNo);
        // TODO: 2019-05-30  上线需要打开 转码
        System.out.println();
        try {
            realName = new String(realName.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        querys.put("realName", realName);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            获取response的body
            String responseStr = EntityUtils.toString(response.getEntity());
            JSONObject responseJson = (JSONObject) JSON.parse(responseStr);
            JSONObject result = (JSONObject) responseJson.get("result");
            Boolean isOk = result.getBoolean("isok");
            System.out.println("身份证第三方结果" + responseJson);
            return isOk;
//            JsonElement isOk = result.get("isOk");
//            return isOk.getAsBoolean();
//            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


//    /**
//     * return
//     *
//     * @param args
//     */
//    public static void main(String[] args) {
//        UserRealInfoService userRealInfoService = new UserRealInfoService();
//        boolean verify = userRealInfoService.verify(UserRealInfoService.idCardNo, UserRealInfoService.realName);
//        System.out.println(verify);
//    }

    /*
     * 获取参数的json对象
     */
    public JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 验证身份证照片
     *
     * @param idCardPhoto
     * @param isFace
     * @param userRealInfo
     * @return
     */
    public BaseDto verifyIdCardPhoto(File idCardPhoto, boolean isFace, UserRealInfo userRealInfo) {
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("side", isFace ? "face" : "back");
        String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        //            String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        // 对图像进行base64编码
        String imgBase64 = "";
        try {

            byte[] content = new byte[(int) idCardPhoto.length()];
            FileInputStream finputstream = new FileInputStream(idCardPhoto);
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
        } catch (IOException e) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg(e.getMessage());
            return baseDto;
        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if (is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if (config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            } else {
                requestObj.put("image", imgBase64);
                if (config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("Http code", stat);
                resultMap.put("http header error msg", response.getFirstHeader("X-Ca-Error-Message"));
                resultMap.put("Http body error msg", EntityUtils.toString(response.getEntity()));

                BaseDto baseDto = new BaseDto();
                baseDto.setCode(CodeConst.ERROR);
                baseDto.setMsg(JSON.toJSONString(resultMap));
                return baseDto;
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);
            if (is_old_format) {
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject out = JSON.parseObject(output);
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(out.get("num")) && userRealInfo.getRealName().equals(out.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(idCardPhoto, isFace, userRealInfo.getId());
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (out.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(idCardPhoto, isFace, userRealInfo.getId());
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }

            } else {
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(res_obj.get("num")) && userRealInfo.getRealName().equals(res_obj.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(idCardPhoto, isFace, userRealInfo.getId());
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (res_obj.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(idCardPhoto, isFace, userRealInfo.getId());
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param fileContent  已被base64编码
     * @param suffix
     * @param isFace
     * @param userRealInfo
     * @return
     * @throws IOException
     */
    public BaseDto verifyIdCardPhoto(String fileContent, String suffix, boolean isFace, UserRealInfo userRealInfo) throws IOException {
        String realPath = new File("").getAbsolutePath();
        String filePath = realPath + File.separator + "tmpDownload" + suffix;
        File file = new File(filePath);
        if (file.exists())
            file.delete();
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = null;
        try {
            bytes = Base64Utils.decodeFromString(fileContent);
        } catch (Exception e) {
            return BaseDto.error("fileContent参数并没有被base64编码");
        }
        inputStream.read(bytes);
        BaseDto baseDto = this.verifyIdCardPhoto(inputStream, suffix, (int) file.length(), true, userRealInfo);
        inputStream.close();
        if (file.exists())
            file.delete();
        if (baseDto.getCode() == CodeConst.ERROR) {

            return baseDto;
        } else {
            return BaseDto.ok(file);
        }
    }

    public BaseDto verifyIdCardPhoto(String objectName, boolean isFace, UserRealInfo userRealInfo) {
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("side", isFace ? "face" : "back");
        String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        //            String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if (is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", ossCommonService.getUrl(bucketName, objectName));
                if (config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            } else {
                requestObj.put("image", ossCommonService.getUrl(bucketName, objectName));
                if (config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("Http code", stat);
                resultMap.put("http header error msg", response.getFirstHeader("X-Ca-Error-Message"));
                resultMap.put("Http body error msg", EntityUtils.toString(response.getEntity()));

                BaseDto baseDto = new BaseDto();
                baseDto.setCode(CodeConst.ERROR);
                baseDto.setMsg(JSON.toJSONString(resultMap));
                System.out.println(LocalDateTime.now().toString() + "=== " + "调用阿里云实名认证异常");
                return baseDto;
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);
            if (is_old_format) {
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject out = JSON.parseObject(output);
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(out.get("num")) && userRealInfo.getRealName().equals(out.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (out.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }

            } else {
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(res_obj.get("num")) && userRealInfo.getRealName().equals(res_obj.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (res_obj.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public BaseDto verifyIdCardPhoto(InputStream idCardPhoto, String suffix, Integer size, boolean isFace, UserRealInfo userRealInfo) {
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("side", isFace ? "face" : "back");
        String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        //            String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        // 对图像进行base64编码
        String imgBase64 = "";
        byte[] content = new byte[size];
        try {


            InputStream finputstream = idCardPhoto;
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
        } catch (IOException e) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg(e.getMessage());
            return baseDto;
        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if (is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if (config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            } else {
                requestObj.put("image", imgBase64);
                if (config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("Http code", stat);
                resultMap.put("http header error msg", response.getFirstHeader("X-Ca-Error-Message"));
                resultMap.put("Http body error msg", EntityUtils.toString(response.getEntity()));

                BaseDto baseDto = new BaseDto();
                baseDto.setCode(CodeConst.ERROR);
                baseDto.setMsg(JSON.toJSONString(resultMap));
                return baseDto;
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);
            if (is_old_format) {
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject out = JSON.parseObject(output);
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(out.get("num")) && userRealInfo.getRealName().equals(out.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(content, suffix, isFace, userRealInfo.getId());
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (out.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(content, suffix, isFace, userRealInfo.getId());
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }

            } else {
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(res_obj.get("num")) && userRealInfo.getRealName().equals(res_obj.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(content, suffix, isFace, userRealInfo.getId());
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (res_obj.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(content, suffix, isFace, userRealInfo.getId());
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传身份证照片
     *
     * @param idCardPhoto
     * @param isFace
     * @param userId
     * @return
     */
    public BaseDto uploadIdCardPhoto(File idCardPhoto, boolean isFace, Integer userId) {
        String bucketName = OssConstant.ossBucketName;
        String fileName = idCardPhoto.getName();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (!suffix.startsWith(".")) {
            suffix += ".";
        }
        String objectName = "userInfo" + userId + "idCard" + (isFace ? "Face" : "Back") + "Photo" + suffix;

        if (!ossCommonService.uploadFile(bucketName, objectName, idCardPhoto)) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg(objectName + "文件上传失败");
            return baseDto;
        }

        /** 存入数据库 **/
        UserRealInfo userRealInfo = getByPrimaryKey(userId);
        if (isFace) {
            userRealInfo.setIdCardFrontPhoto(bucketName + "/" + objectName);
        } else {
            userRealInfo.setIdCardBackPhoto(bucketName + "/" + objectName);
        }
        update(userRealInfo);

        BaseDto baseDto = new BaseDto();
        baseDto.setData(objectName + "上传完成");
        return baseDto;
    }

    /**
     * 上传身份证照片
     *
     * @param content
     * @param suffix
     * @param isFace
     * @param userId
     * @return
     */
    public BaseDto uploadIdCardPhoto(byte[] content, String suffix, boolean isFace, Integer userId) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAIQb8xLiRdju3q";
        String accessKeySecret = "1G6AFqff9UyONRy8zroKpu8UZjfnZj";
        String bucketName = OssConstant.ossBucketName;
        if (!suffix.startsWith(".")) {
            suffix += ".";
        }
        String objectName = "userInfo-" + userId + "-idCard" + (isFace ? "Face" : "Back") + "Photo" + suffix;


        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        if (!ossCommonService.uploadFile(bucketName, objectName, content, suffix)) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("文件写入错误");
        }

        if (isFace) {
            UserRealInfo userRealInfo = getByPrimaryKey(userId);
            if (isFace) {
                userRealInfo.setIdCardFrontPhoto(objectName);
            } else {
                userRealInfo.setIdCardBackPhoto(objectName);
            }
        }
        BaseDto baseDto = new BaseDto();
        baseDto.setData(objectName + "上传完成");
        return baseDto;
    }

    /**
     * 上传手持身份证照片
     *
     * @param content
     * @param suffix
     * @param userId
     * @return
     */
    public BaseDto uploadTakingCardPhoto(byte[] content, String suffix, Integer userId) {

        if (!suffix.startsWith(".")) {
            suffix += ".";
        }
        String objectName = "userInfo" + userId + "takingCard" + "Photo" + suffix;

        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        if (!ossCommonService.uploadFile(bucketName, objectName, content, suffix)) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("文件写入错误");
        }

        /** 存入数据库 **/
        UserRealInfo userRealInfo = getByPrimaryKey(userId);
        userRealInfo.setTakingCardPhoto(bucketName + "/" + objectName);
        update(userRealInfo);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(objectName + "上传完成");
        return baseDto;
    }

    /**
     * 获取照片
     *
     * @param userId
     * @return
     */
    public UserRealInfo getPhotosByUserId(Integer userId) {
        UserRealInfo userRealInfo = getByPrimaryKey(userId);
        String idCardFrontPhoto = userRealInfo.getIdCardFrontPhoto();
        if (StringUtils.hasText(idCardFrontPhoto)) {
            userRealInfo.setIdCardFrontPhotoUrl(getUrl(idCardFrontPhoto));
        }
        String takingCardPhoto = userRealInfo.getTakingCardPhoto();
        if (StringUtils.hasText(takingCardPhoto)) {
            userRealInfo.setIdCardFrontPhotoUrl(takingCardPhoto);
        }
        return userRealInfo;
    }


    public String getUrl(String path) {
        String objectName = path;
        return ossCommonService.getUrl(bucketName, objectName);
    }

    public byte[] getFileContent(String path) {

        String objectName = path;
        return ossCommonService.getFileContent(bucketName, objectName);
    }

    public Integer getUserIdByPhoneNumAndIdCard(String phoneNum, String IdCardNum) {
        Integer userId = 0;
        if (phoneNum != null) {
            userId = userInfoBindService.getByPhoneNum(phoneNum).getId();
        }
        if (IdCardNum != null) {
            UserRealInfo userRealInfo = new UserRealInfo();
            userRealInfo.clearCreateTimeAndUpdateTime();
            userRealInfo.setIdCardNum(IdCardNum);
            userId = get(userRealInfo).getId();
        }
        return userId;
    }

    @Override
    protected void complete(UserRealInfo bean) {
        bean.setCardTypeName(cardTypeService.getByPrimaryKey(bean.getCardTypeId()).getName());
    }

    public List<UserRealInfo> getAllNeedVerify() {
        CommonExample example = new CommonExample(UserRealInfo.class);
        example.equals("verified", 0);
        return getsByExampleWithoutComplete(example);
    }

    public boolean insertable(String idCardNum) {
        CommonExample example = new CommonExample(UserRealInfo.class);
        example.equals("idCardNum", idCardNum);
        List<UserRealInfo> userRealInfos = getsByExampleWithoutComplete(example);
        if (userRealInfos != null && !userRealInfos.isEmpty())
            return false;
        return true;
    }

    public boolean insertable(String idCardNum, Integer cardTypeId) {
        CommonExample example = new CommonExample(UserRealInfo.class);
        example.equals("cardTypeId", cardTypeId);
        example.equals("idCardNum", idCardNum);
        List<UserRealInfo> userRealInfos = getsByExampleWithoutComplete(example);
        if (userRealInfos != null && !userRealInfos.isEmpty())
            return false;
        return true;
    }

    public boolean checkAbleChange(Integer userId) {
        UserRealInfo userRealInfo = getByPrimaryKey(userId);
        //用户未实名认证
        if (userRealInfo == null || userRealInfo.getVerified() != 1) {
            User user = userService.getByPrimaryKey(userId);
            if (user.getRegistType() == 1) {
                return false;
            }else {
                UserInfoBind userInfoBind = userInfoBindService.getByPrimaryKey(userId);
                String phoneNum = userInfoBind.getPhoneNum();
                String sPhoneNum = userInfoBind.getSPhoneNum();
                if (phoneNum.equals(sPhoneNum)){
                    return true;
                }else {
                    return false;
                }
            }
        }else {
            return true;
        }
    }
}